package com.bw.finance.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.finance.auth.UserInfo;
import com.bw.finance.client.FinanceUserClient;
import com.bw.finance.conf.ResponseResult;
import com.bw.finance.eneity.BidAndLoan.EbidAndLoan;
import com.bw.finance.eneity.locana.*;
import com.bw.finance.eneity.locana.res.Borrowinfo;
import com.bw.finance.eneity.locana.res.Respath;
import com.bw.finance.eneity.user.EbankBorrower;
import com.bw.finance.mapper.EbankLoanInfoMapper;
import com.bw.finance.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.management.Query;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lizhengqian
 * @since 2020-08-18
 */
@Service
public class EbankLoanInfoServiceImpl extends ServiceImpl<EbankLoanInfoMapper, EbankLoanInfo> implements IEbankLoanInfoService {

    @Resource
    private FinanceUserClient financeUserClient;
    @Resource
    private EbankLoanInfoMapper ebankLoanInfoMapper;

    @Autowired
    private IEbankResService resService;

    @Autowired
    private IEbankMgInfoService mgInfoService;

    @Autowired
    private IEbankLoanResService loanResService;

    @Resource
    private IEbankLoanInfoService iEbankLoanInfoService;

    @Autowired
    private IEbankApprovalLogService approvalLogService;

    private final Logger logger = LoggerFactory.getLogger(ServiceImpl.class);
   /* @Override
    public ResponseResult AddOne(Integer cks, Long userid, EbankLoanInfo info) {
        logger.info("新增借款人开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            if(info!=null){
                if(cks==1){
                    info.setStatus(1);//设置为提交
                }else if(cks==0){
                    info.setStatus(0);//设置为草稿
                }
                info.setCreateTime(new Date());
                info.setUpdateTime(new Date());
                info.setApprover(userid);
            }
            ebankLoanInfoMapper.insert(info);
            result.setMessage("添加成功");
        } catch (Exception e) {
            logger.error("添加借款人异常，{}" + e.toString());
            result.setSuccess(false);
            result.setMessage("添加失败" + e.toString());
        }
        logger.info("新增借款人结束");
        return result;
    }*/

    @Override
    @Transactional
    public ResponseResult addloan(Borrowinfo borrowinfo) {
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            EbankLoanInfo loaninfo = borrowinfo.getLoaninfo();
            loaninfo.setCreateTime(new Date());
            ebankLoanInfoMapper.insert(loaninfo);
            List<Respath> pathlist = borrowinfo.getPathlist();
            for (Respath rp:pathlist) {
                QueryWrapper<EbankRes> queryWrapper=new QueryWrapper();
                queryWrapper.lambda().eq(EbankRes::getExt,rp.getName());
                EbankRes res = resService.getOne(queryWrapper);
                if(res!=null){
                    if(res.getResType()==0){
                        EbankMgInfo ebankMgInfo = new EbankMgInfo();
                        ebankMgInfo.setLidId(loaninfo.getId());
                        ebankMgInfo.setGrtId(borrowinfo.getMginfo().getGrtId());
                        ebankMgInfo.setType(borrowinfo.getMginfo().getType());
                        ebankMgInfo.setMgResId(res.getId());
                        mgInfoService.saveOrUpdate(ebankMgInfo);
                    }
                    if(res.getResType()==1){
                        EbankLoanRes loanRes = new EbankLoanRes();
                        loanRes.setLid(loaninfo.getId());
                        loanRes.setRid(res.getId());
                        loanResService.saveOrUpdate(loanRes);
                    }
                }
            }
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("添加失败" + e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult invlist(int pagenum, int pagesize, EbankLoanInfo ebankLoanInfo) {
        logger.info("开始查询借款的信息列表");
        ResponseResult result = ResponseResult.SUCCESS();
        try{
            PageHelper.startPage(pagenum,pagesize);
            QueryWrapper<EbankLoanInfo> queryWrapper = new QueryWrapper<>();
//            审核通过2/不通过3 新标待审核1 可以发标的数据4
            queryWrapper.lambda().orderByDesc(EbankLoanInfo::getCreateTime).between(EbankLoanInfo::getStatus,1,3);
//                    gt(EbankLoanInfo::getStatus,1).lt(EbankLoanInfo::getStatus,3);
            if(ebankLoanInfo!=null){//模糊/
                if(ebankLoanInfo.getBorrowerId()!=null){//精确
                    queryWrapper.lambda().eq(EbankLoanInfo::getBorrowerId,ebankLoanInfo.getBorrowerId());
                }
            }
            List<EbankLoanInfo> loanInfoList = ebankLoanInfoMapper.selectList(queryWrapper);
            for (EbankLoanInfo e:loanInfoList) {
                Long borrowerId = e.getBorrowerId();//取到借款人的id

//                查询借款对象，给借款信息借款人虚拟字段赋值
                EbankBorrower getborrowone = financeUserClient.getborrowone(e);
                e.setFullName(getborrowone.getFullName());
            }

            PageInfo pageInfo = new PageInfo<>(loanInfoList);//分页
            result.setResult(pageInfo);
            logger.info("查询列表信息结束");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
        }

        return result;
    }

    @Override
    public ResponseResult updatestate(String id, int val) {
        logger.info("开始审核");
        ResponseResult result = ResponseResult.SUCCESS();
        try{
            EbankLoanInfo byId = iEbankLoanInfoService.getById(id);
            byId.setStatus(val);
            iEbankLoanInfoService.saveOrUpdate(byId);
            logger.info("审核结束");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult findone(int id) {
        logger.info("开始查询某个数据");
        ResponseResult result = ResponseResult.SUCCESS();
        try{
            EbankLoanInfo byId = iEbankLoanInfoService.getById(id);
            result.setResult(byId);
            logger.info("查询结束");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult newlist(int pagenum, int pagesize, EbankLoanInfo ebankLoanInfo) {
        logger.info("开始查询借款的信息列表");
        ResponseResult result = ResponseResult.SUCCESS();
        try{
            PageHelper.startPage(pagenum,pagesize);
            QueryWrapper<EbankLoanInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().orderByDesc(EbankLoanInfo::getCreateTime);
            queryWrapper.lambda().eq(EbankLoanInfo::getStatus,0);
            queryWrapper.lambda().or();
            queryWrapper.lambda().eq(EbankLoanInfo::getStatus,1);
            if(ebankLoanInfo!=null){//模糊/
                if(ebankLoanInfo.getBorrowerId()!=null){//精确
                    queryWrapper.lambda().eq(EbankLoanInfo::getBorrowerId,ebankLoanInfo.getBorrowerId());
                }
            }
            List loanInfoList = ebankLoanInfoMapper.selectList(queryWrapper);
            PageInfo pageInfo = new PageInfo<>(loanInfoList);//分页
            result.setResult(pageInfo);
            logger.info("查询列表信息结束");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
        }
        return result;
    }

    @Override
    public ResponseResult findform(Long loanid) {
        logger.info("借款信息回显开始");
        ResponseResult result = ResponseResult.SUCCESS();
        try{
            List<Respath> list=new ArrayList<>();
            EbankLoanInfo loanInfo = iEbankLoanInfoService.getById(loanid);
            Borrowinfo borrowinfo = new Borrowinfo();
            borrowinfo.setLoaninfo(loanInfo);
            QueryWrapper<EbankMgInfo> queryWrapper=new QueryWrapper();
            queryWrapper.lambda().eq(EbankMgInfo::getLidId,loanid);
            List<EbankMgInfo> mgInfoList = mgInfoService.list(queryWrapper);
            for (EbankMgInfo emi:mgInfoList) {
                EbankRes res = resService.getById(emi.getMgResId());
                Respath respath = new Respath();
                respath.setName(res.getExt());
                respath.setType(0);
                list.add(respath);
            }
            QueryWrapper<EbankLoanRes> queryWrapper1=new QueryWrapper();
            queryWrapper1.lambda().eq(EbankLoanRes::getLid,loanid);
            List<EbankLoanRes> loanResList = loanResService.list(queryWrapper1);
            for (EbankLoanRes elr:loanResList) {
                EbankRes res = resService.getById(elr.getRid());
                Respath respath = new Respath();
                respath.setName(res.getExt());
                respath.setType(1);
                list.add(respath);
            }
            borrowinfo.setPathlist(list);
            borrowinfo.setMginfo(mgInfoList.get(0));
            result.setResult(borrowinfo);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
        }
        logger.info("借款信息回显结束");
        return result;
    }

    @Override
    public void updateloan(EbankLoanInfo loanInfo,Long id) {
        loanInfo.setUpdateTime(new Date());
        iEbankLoanInfoService.saveOrUpdate(loanInfo);
        EbankApprovalLog approvalLog = new EbankApprovalLog();
        approvalLog.setLid(loanInfo.getId());
        approvalLog.setApprover(id);
        approvalLog.setActionTime(new Date());
        approvalLog.setOpinion("新标维护");
        approvalLogService.saveOrUpdate(approvalLog);
    }

    /*@Override
    public ResponseResult getborrowall(int pagenum, int pagesize, EbankBorrower borrower) {
        logger.info("开始查询");
        ResponseResult result = ResponseResult.SUCCESS();
        try{
            PageHelper.startPage(pagenum, pagesize);

            List<EbankLoanInfo> list= ebankLoanInfoMapper.jieklist();
            PageInfo pageInfo = new PageInfo(list);
            result.setSuccess(true);
            result.setMessage("查询成功!");
            result.setResult(pageInfo);
            logger.info("查询结束");
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage(e.toString());
            logger.error(e.toString());
        }
        return result;
    }*/

    @Override
    public ResponseResult getBorrowerList(int pagenum, int pagesizes,EbankBorrower ebankBorrower) {
        ResponseResult result = ResponseResult.SUCCESS();
        PageHelper.startPage(pagenum,pagesizes);
        try {
            HashMap<Object, Object> map = new HashMap<>();

            if(ebankBorrower.getFullName()!=null){
                map.put("fullName",ebankBorrower.getFullName());
            }
            List<EbankLoanInfo> loanInfos = ebankLoanInfoMapper.getBorrowerList(map);
            PageInfo pageInfo = new PageInfo(loanInfos);
            result.setResult(pageInfo);
        }catch (Exception e){
            result.setSuccess(false);
            result.setMessage("查询失败");
            e.printStackTrace();
        }
        return result;
    }

}
